package com.ambitor.ipro.actions;

import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.json.annotations.JSON;

import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.IData;
import com.ambitor.ipro.entities.Result;
import com.ambitor.ipro.service.InstallService;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.ResultCode;
import com.ambitor.ipro.util.StringUtil;

public class InstallAction extends BaseAction {

	private transient Map<String, String> ipro;

	private transient Map<String, String> userStyle;

	private transient InstallService installService;

	private Result result = new Result();

	private static final long serialVersionUID = -5524240766566189217L;

	public InstallAction() throws SQLException {
		try {
			installService = new InstallService(pd.getConn());
		} catch (SQLException e) {
			e.printStackTrace();
			logger.warn(pd.getTopNick() + "InstallAction()初始化出现异常", e);
			throw e;
		}
	}

	@JSON(serialize = false)
	public Map<String, String> getUserStyle() {
		return userStyle;
	}

	public void setUserStyle(Map<String, String> userStyle) {
		this.userStyle = userStyle;
	}

	@JSON(serialize = false)
	public Map<String, String> getIpro() {
		return ipro;
	}

	public void setIpro(Map<String, String> ipro) {
		this.ipro = ipro;
	}

	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		this.result = result;
	}

	@SuppressWarnings("unchecked")
	public String install() throws Exception {
		logger.warn("InstallAction.install() running...");
		if (ipro == null || ipro.size() == 0) {
			result.setCode(ResultCode.INPUT_PARAM_IS_NULL);
			logger.error(pd.getTopNick() + "input parameter ipro is null");
			return SUCCESS;
		}
		try {
			IData iproMap = new DataMap(ipro);
			IData proSetting = buildProSetting(iproMap);
			// IData userStyleMap = buildUserStyle();
			IData userSession = pd.getUserSession();
			installService.saveProSettings(proSetting, new DataMap(userStyle),
					userSession);// 保存推广配置
		} catch (Exception e) {
			this.rollback();
			logger.error(pd.getTopNick() + "安装推广模块出现异常", e);
			result.setCode(ResultCode.ERROR);
			result.setMsg(e.getMessage());
			return SUCCESS;
		}
		installService.installCount(pd.getUserSession(), pd
				.getTopUserSubscribe());// 安装计数器代码
		result.setCode(ResultCode.SUCCESS);
		pd.RemoveSessionAttribute(Constants.PRO_SETTING);
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	private IData buildProSetting(IData iproMap) {
		IData proSetting = new DataMap();
		proSetting.put("USER_ID", pd.getTopUserId());
		proSetting.put("NICK", pd.getTopNick());
		proSetting.put("INSTALL_SETTING", iproMap.getString("promote_radio"));
		proSetting.put("CATEGORIES", iproMap.getString("install_cids"));
		proSetting.put("INSTALL_IIDS", iproMap.getString("to_promote_iids"));
		proSetting.put("INSTALL_PLACE", iproMap.getString("install_place"));

		String isIntellClose = iproMap.getString("is_intell_close");
		if ("INTELL_OFF".equalsIgnoreCase(isIntellClose)) {
			proSetting.put("INTELL_NUM", 0);
		} else {
			Integer[] intellIntegerNums = StringUtil.strArrayToIntArray(iproMap
					.getString("intell_nums").split(","));
			int intellNums = StringUtil.sum(intellIntegerNums);
			proSetting.put("INTELL_NUM", intellNums);
		}

		if (proSetting.getInt("INTELL_NUM") <= 0) {
			proSetting.put("INTELL_SETTING", "");
			proSetting.put("FREQUENCY", -1);
		} else {
			String[] intellLables = iproMap.getString("intell_labels").split(
					",");
			String[] intellNums = iproMap.getString("intell_nums").split(",");
			StringBuilder intellSetting = new StringBuilder();
			for (int i = 0; i < intellNums.length; i++) {
				if (StringUtils.isBlank(intellNums[i])
						|| "0".equals(StringUtils.trimToEmpty(intellNums[i]))) {
					continue;
				} else {
					intellSetting.append(intellLables[i] + ":" + intellNums[i]
							+ ",");
				}
			}
			String intellSettingStr = StringUtil.trimSuffix(intellSetting
					.toString(), ",");

			proSetting.put("INTELL_SETTING", intellSettingStr);
			proSetting.put("FREQUENCY", iproMap.getString("intell_frequency"));
		}

		if (StringUtils.isBlank(iproMap.getString("be_promoted_iids"))) {
			proSetting.put("STATIC_NUM", 0);
			proSetting.put("STATIC_SETTING", "");
		} else {
			int staticNum = (iproMap.getString("be_promoted_iids").split(",")).length;
			proSetting.put("STATIC_NUM", staticNum);
			proSetting.put("STATIC_SETTING", iproMap
					.getString("be_promoted_iids"));
		}
		return proSetting;
	}
}